import json
import os
import re
from urllib.parse import urlsplit

from jinja2 import Environment
from utils.project_path import config


class Har2ApiUtil():
    """
        将Har文件转换为Py文件

    """

    @staticmethod
    def har2api(har_file_name):

        env = Environment()
        env.filters["remove_key"] = remove_key
        temp = """{%- for dict_item in parent_dict -%}{% if loop.index == 1 %}from utils.base_api import BaseApi{% endif %}

    
class {{ dict_item.get('filename') }}(BaseApi):
   {% set new_dict = dict_item|remove_key("filename") %}
   {% for key, value in new_dict.items() %}
    {{ key }} = {{ value }}
   {%- endfor -%}
{%- endfor -%}
"""
        template = env.from_string(temp)

        result = []
        har_file_path = os.path.join(config.HAR_PATH, har_file_name)

        with open(har_file_path, 'r', encoding="utf-8-sig") as f:
            har_content = ""
            for line in f.readlines():
                har_content += line

            load_dict = json.loads(har_content)
            entries = load_dict.get('log').get('entries')

            for entry in entries:

                temp_dict = dict()
                request = entry.get('request')

                temp_dict['path'] = "\"" + urlsplit(request.get('url')).path + "\""
                temp_dict['method'] = "\"" + request.get('method') + "\""

                # 先将headers数组类型转成字典类型,再转成字符串
                headers = request.get('headers')
                headers_dict = dict()
                for header in headers:
                    headers_dict[header['name']] = header['value']
                temp_dict['headers'] = str(headers_dict)

                if request.get('method') != 'GET':
                    mimeType = request.get('postData').get('mimeType')

                    # 如果请求数据类型为JSON,则生成JSON数据
                    if mimeType == 'application/json':
                        json_str = request.get('postData').get('text')
                        json_dict = json.loads(json_str)
                        temp_dict['json'] = json_dict
                    else:
                        pass

                # 如果queryString不为空,则生成param数据
                queryString = request.get('queryString')
                if len(queryString) != 0:

                    query_dict = dict()
                    for qtr in queryString:
                        query_dict[qtr['name']] = qtr['value']
                    temp_dict['params'] = str(query_dict)

                temp_dict['filename'] = Har2ApiUtil.__name_convert_to_camel(os.path.basename(urlsplit(request.get('url')).path))
                if temp_dict['method'] != 'OPTIONS':
                    result.append(temp_dict)
        # 渲染模板
        file_content = template.render(parent_dict=result)
        pypath = ''.join([config.API_PATH, os.sep, har_file_name.replace('har', 'py')])

        with open(pypath, "w") as f:
            f.write(file_content)

    @staticmethod
    def __name_convert_to_camel(name: str) -> str:
        """下划线转驼峰"""
        contents = re.findall('_[a-z]+', name)
        for content in set(contents):
            name = name.replace(content, content[1:].title())
        return "".join(name[:1].upper() + name[1:])


def remove_key(d, key):
    new_dict = d.copy()
    new_dict.pop(key)
    return new_dict


if __name__ == '__main__':
    Har2ApiUtil.har2api("vue.har")
